package com.controller;

import com.bean.GoodImg;
import com.config.MinioClientConfig;
import com.service.GoodImgService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @ClassName : ImgFileUpload
 * @Auther : acerolan@foxmail.com
 * @Data : 2024/9/12 14:31
 * @Description :
 */
@RestController
public class GoodImgFileUpload {

    @Autowired
    GoodImgService goodImgService;

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioClientConfig minioClientConfig;

    @PostMapping("/good/imgUpload")
    @CrossOrigin(methods = {RequestMethod.POST}, value = "*")
    public String upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") int userId,
            @RequestParam("goodId") int goodId
                ) throws Exception {

        String bucket = minioClientConfig.getBucket();
        String filepath = this.getGoodFilepath(userId, goodId) + file.getOriginalFilename();

        this.minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucket)
                        .object(filepath) // 文件的路径
                        .stream(file.getInputStream(), -1L, 10485760L)
                        .build()
        );

        // 上传后存入数据库
        GoodImg goodImg = new GoodImg();
        List<GoodImg> goodImgs = goodImgService.selectAllGoodImgByGoodId(goodId);
        goodImg.setNo(goodImgs.size()+1);
        goodImg.setSrc(filepath);
        goodImg.setGoodId(goodId);

        goodImgService.insertGoodImg(goodImg);

        return filepath;
    }

    private String getGoodFilepath(int userId, int goodId) {
        String filePath = "img/goods/";

        return filePath + userId + "/" + goodId + "/";
    }

}
